package logic

import (
	"context"
	"net/http"
	"time"

	"probe-tools/internal/svc"
	"probe-tools/pb/probe"

	"github.com/zeromicro/go-zero/core/logx"
)

type HttpProbeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHttpProbeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HttpProbeLogic {
	return &HttpProbeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HttpProbeLogic) HttpProbe(in *probe.HttpProbeRequest) (*probe.HttpProbeResponse, error) {
	start := time.Now()
	timeout := time.Duration(in.Timeout) * time.Second
	if in.Timeout <= 0 {
		timeout = 5 * time.Second // 默认超时5秒
	}

	// 创建HTTP客户端
	client := &http.Client{
		Timeout: timeout,
	}

	// 发送HEAD请求(减少数据传输)
	req, err := http.NewRequestWithContext(l.ctx, http.MethodHead, in.Url, nil)
	if err != nil {
		return &probe.HttpProbeResponse{
			Success:  false,
			Duration: time.Since(start).Milliseconds(),
			Error:    err.Error(),
		}, nil
	}

	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")
	req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
	req.Header.Set("Accept-Language", "en-US,en;q=0.5")

	resp, err := client.Do(req)
	if err != nil {
		return &probe.HttpProbeResponse{
			Success:  false,
			Duration: time.Since(start).Milliseconds(),
			Error:    err.Error(),
		}, nil
	}
	defer resp.Body.Close()

	return &probe.HttpProbeResponse{
		Success:  true,
		Status:   int32(resp.StatusCode),
		Duration: time.Since(start).Milliseconds(),
		Type:     "http",
	}, nil
}
